package com.xiaolei.library.Base;

import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public abstract class BaseAdapter<DataType> extends android.widget.BaseAdapter
{
    private List<DataType> innerList = new LinkedList<>();
    public List<DataType> list = null;

    public BaseAdapter()
    {
        this(null);
    }

    public BaseAdapter(List<DataType> list)
    {
        if (list == null)
        {
            list = new ArrayList<>();
        }
        this.list = list;
    }


    @Override
    public boolean isEmpty()
    {
        return innerList.isEmpty();
    }

    @Override
    public DataType getItem(int index)
    {
        return innerList.get(index);
    }

    @Override
    public long getItemId(int index)
    {
        return index;
    }

    @Override
    public int getCount()
    {
        return innerList.size();
    }

    @Override
    public void notifyDataSetChanged()
    {
        innerList.clear();
        innerList.addAll(list);
        super.notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        DataType data = innerList.get(position);
        BaseHolder holder;
        if (convertView == null)
        {
            holder = onCreate(parent, getItemViewType(position));
            convertView = holder.itemView;
            convertView.setTag(holder);
        } else
        {
            holder = (BaseHolder) convertView.getTag();
        }
        onBindView(holder, data, position);
        return convertView;
    }

    /**
     * View 的创建
     *
     * @param parent   父控件
     * @param viewType 类型
     * @return
     */
    public abstract BaseHolder onCreate(ViewGroup parent, int viewType);

    /**
     * ViewHolder与数据的绑定
     *
     * @param holder   viewHoler对象
     * @param data     数据
     * @param position 定位
     */
    public abstract void onBindView(BaseHolder holder, DataType data, int position);
}
